package com.example.nccdeploytool.controller;

import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.TextField;

import java.io.InputStream;
import java.net.URL;
import java.util.ResourceBundle;

/**
 * ssh 登录
 *
 * @author 15037
 * @description
 * @date 2025-07-16 14:50
 */
public class SshLoginController implements Initializable {


    @FXML
    TextField txtUser;
    @FXML
    TextField txtPwd;


    @Override
    public void initialize(URL url, ResourceBundle resourceBundle) {

    }

    public void btnLoginClick(ActionEvent actionEvent) {
        System.out.println("login");
        String user = txtUser.getText();
        String password = txtPwd.getText();
        String host = "your.host.com";
        int port = 22;

        try {
            JSch jsch = new JSch();
            Session session = jsch.getSession(user, host, port);
            session.setPassword(password);
            session.setConfig("StrictHostKeyChecking", "no");
            session.connect();

            System.out.println("Connected successfully!");

            ChannelExec channel = (ChannelExec) session.openChannel("exec");
            channel.setCommand("ls -l");

            // 读取命令输出...
            // 获取输入流以读取命令输出
            InputStream in = channel.getInputStream();
            channel.connect();

            // 读取输出内容
            byte[] buffer = new byte[1024];
            int bytesRead;
            StringBuilder output = new StringBuilder();

            while ((bytesRead = in.read(buffer)) > 0) {
                output.append(new String(buffer, 0, bytesRead));
            }

            System.out.println("命令输出:\n" + output.toString());


            channel.disconnect();
            session.disconnect();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
